package com.tan.androidtest.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;

/**
 * 和activity通讯的service
 */

public class TestConnectActivityService extends Service {

    private static final int MSG_SEND_MESSAGE = 0x111;
    private Handler mHandler;
    private int mProcess = 0;

    private OnProcessListener mListener;

    @Override
    public void onCreate() {
        super.onCreate();
        if (mHandler == null) {
            mHandler = new MyHandler();
        }
        mHandler.sendEmptyMessageDelayed(MSG_SEND_MESSAGE, 3000);
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    public class MyBinder extends Binder {

        public TestConnectActivityService getService() {
            return TestConnectActivityService.this;
        }
    }

    class MyHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            mProcess += 5;
            mHandler.sendEmptyMessageDelayed(MSG_SEND_MESSAGE, 3000);
            if (mListener != null) {
                mListener.onProcess(mProcess);
            }
        }
    }


    public interface OnProcessListener {
        void onProcess(int process);
    }


    public void setOnProcessListener(OnProcessListener listener) {
        mListener = listener;
    }

}
